package com.china.controller;

import com.china.constants.SystemConstants;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class ParagraphBasedKnowledgeInitializer {


    private final VectorStore vectorStore;
    private final ObjectMapper objectMapper;

    // 用@Bean定义ApplicationRunner，确保应用启动时执行
    @Bean
    public ApplicationRunner loadRuleToVectorStore() {
        return args -> {
            try {
                // 1. 打印启动日志，确认执行
                log.info("===== 开始加载系统预设规则到向量库 =====");

                // 2. 获取SystemConstants中的JSON规则
                String jsonRule = SystemConstants.SYSTEM_KNOWLEDGE_STRINGS;
                if (jsonRule == null || jsonRule.trim().isEmpty()) {
                    log.error("===== 系统规则为空，加载失败 =====");
                    return;
                }

                // 3. 解析JSON为规则列表
                List<Map<String, String>> rules = objectMapper.readValue(
                        jsonRule, new TypeReference<List<Map<String, String>>>() {});
                log.info("===== 解析到 {} 条系统规则 =====", rules.size()); // 正常应输出2条

                // 4. 转换为Document并添加到向量库
                List<Document> docs = new ArrayList<>();
                for (Map<String, String> rule : rules) {
                    String id = rule.get("id"); // 取rule_01/rule_02作为文档ID
                    // 构建清晰的规则内容，便于检索匹配
                    String content = String.format("规则ID：%s，类型：%s，条件：%s，描述：%s",
                            rule.get("id"), rule.get("type"), rule.get("condition"), rule.get("description"));
                    // 元数据（可选，至少传空Map）
                    Map<String, Object> meta = new HashMap<>();
                    meta.put("ruleType", rule.get("type"));

                    docs.add(new Document(id, content, meta));
                    log.info("===== 已添加规则：{} =====", content); // 打印每条规则，确认添加
                }

                // 5. 写入向量库
                vectorStore.add(docs);
                log.info("===== 系统规则全部加载到向量库，共 {} 条 =====", docs.size());

            } catch (Exception e) {
                log.error("===== 系统规则加载失败！原因：{} =====", e.getMessage(), e);
            }
        };
    }
}